package com.tebiecloud.mpweixin.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tebiecloud.common.security.SecurityHelper;
import com.tebiecloud.common.security.SecurityUserDetails;
import com.tebiecloud.common.utils.DateUtils;
import com.tebiecloud.common.utils.RedisUtils;
import com.tebiecloud.mpweixin.client.constants.MpweixinConstants;
import com.tebiecloud.mpweixin.client.model.entity.MpweixinMggFlow;
import com.tebiecloud.mpweixin.client.model.entity.MpweixinUserFlow;
import com.tebiecloud.mpweixin.client.model.entity.MpweixinUserWallet;
import com.tebiecloud.mpweixin.client.model.vo.FundsFlowListVO;
import com.tebiecloud.mpweixin.server.mapper.MpweixinMggFlowMapper;
import com.tebiecloud.mpweixin.server.mapper.MpweixinUserWalletMapper;
import com.tebiecloud.mpweixin.server.service.MpweixinMggFlowService;
import com.tebiecloud.common.mybatis.base.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户乖乖币记录表 服务实现类
 * @author tebie
 * @date 2019-09-16
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class MpweixinMggFlowServiceImpl extends BaseServiceImpl<MpweixinMggFlowMapper, MpweixinMggFlow> implements MpweixinMggFlowService {

    @Autowired
    MpweixinMggFlowMapper mpweixinMggFlowMapper;

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    MpweixinUserWalletMapper mpweixinUserWalletMapper;

    @Override
    public IPage<FundsFlowListVO> selectFundsFlowList(Integer page, Integer limit) {
        IPage<FundsFlowListVO> fundsFlowListVOIPage = new Page<FundsFlowListVO>();
        SecurityUserDetails securityUserDetails = SecurityHelper.getUser();
        if(securityUserDetails!=null && securityUserDetails.getUserId()!=null){
            QueryWrapper<MpweixinMggFlow> mpweixinUserFlowQueryWrapper = new QueryWrapper<MpweixinMggFlow>();
            mpweixinUserFlowQueryWrapper.eq("user_id",securityUserDetails.getUserId());
            mpweixinUserFlowQueryWrapper.orderByDesc("ct");
            IPage<MpweixinMggFlow> mpweixinMggFlowIPage = mpweixinMggFlowMapper.selectPage(new Page<MpweixinMggFlow>(page,limit),mpweixinUserFlowQueryWrapper);
            if(mpweixinMggFlowIPage.getPages()>0){
                List<FundsFlowListVO> fundsFlowListVOS = new ArrayList<FundsFlowListVO>();
                for(MpweixinMggFlow mpweixinMggFlow:mpweixinMggFlowIPage.getRecords()){
                    FundsFlowListVO fundsFlowListVO = new FundsFlowListVO();
                    fundsFlowListVO.setCt(DateUtils.formatDate(mpweixinMggFlow.getCt(),"yyyy-MM-dd HH:mm:ss"));
                    fundsFlowListVO.setNumber(mpweixinMggFlow.getOrderId());
                    fundsFlowListVO.setTransactionFunds(mpweixinMggFlow.getTransactionFunds());
                }
            }
        }
        return fundsFlowListVOIPage;
    }

    @Override
    public Map<String, String> saveCoinFlow(Long userId, Long number, int amount, int type) {
        Map<String, String> resultMap = new HashMap<String, String>();
        int time = 5;
        String key = MpweixinConstants.REDIS_COIN_FLOW_+userId;
        boolean isLock = redisUtils.lock(key, time);
        if(!isLock){
            throw new RuntimeException("资金池被占用，请稍等");
        }
        //查询钱包
        QueryWrapper<MpweixinUserWallet> mpweixinUserWalletQueryWrapper = new QueryWrapper<>();
        mpweixinUserWalletQueryWrapper.eq("user_id",userId);
        MpweixinUserWallet mpweixinUserWallet =mpweixinUserWalletMapper.selectOne(mpweixinUserWalletQueryWrapper);
        //计算交易的资金
        int futureFunds = 0;
        //交易类型：1、核销获得乖乖币，2、支付消费乖乖币，3、关闭订单退返，4、订单退款退返、5评论返币、6领取乖乖币
        if(type==1||type==3||type==5||type==6){
            futureFunds = mpweixinUserWallet.getMgg() + amount;
        }
        if(type==2||type==4){
            futureFunds = mpweixinUserWallet.getMgg() - amount;
        }
        MpweixinMggFlow mpweixinMggFlow = new MpweixinMggFlow();
        mpweixinMggFlow.setUserId(userId);
        mpweixinMggFlow.setOrderId(number);
        mpweixinMggFlow.setTransactionType(type);
        mpweixinMggFlow.setFutureFunds(futureFunds);
        mpweixinMggFlow.setResidueFunds(mpweixinUserWallet.getBalance());
        mpweixinMggFlow.setTransactionFunds(amount);
        mpweixinMggFlowMapper.insert(mpweixinMggFlow);
        //解锁
        redisUtils.unLock(key);
        return resultMap;
    }
}
